package org.ecloud.core.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.ecloud.common.constants.StateEnum;
import org.ecloud.common.constants.StringPool;
import org.ecloud.core.entity.APIResult;
import org.slf4j.LoggerFactory;

public class GatewayFilter implements Filter {

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {

	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		
		LoggerFactory.getLogger(getClass()).debug("client gateway filter.");
		
		request.setCharacterEncoding(StringPool.UTF_8);
		response.setCharacterEncoding(StringPool.UTF_8);
		
		HttpServletRequest httpRequest = (HttpServletRequest) request;

		// 校验网关属性
		String fromGateway = httpRequest.getHeader("from_gateway");
		if(StringPool.Y.equalsIgnoreCase(fromGateway)){
			chain.doFilter(request, response);
		} else {
			APIResult<Void> result = new APIResult<>();
			result.setCode(StateEnum.ILLEGAL_REQUEST.getCode());
			result.setMessage(StateEnum.ILLEGAL_REQUEST.getText());
			result.setCause(StateEnum.ILLEGAL_REQUEST.getText());
			
			response.getWriter().print(result.toString());
		}
	}

	@Override
	public void destroy() {

	}

}
